package com.vision.world.survey.managers;

import android.content.Context;
import android.util.Log;
import android.view.MotionEvent;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.data.FeatureTable;
import com.esri.arcgisruntime.data.Field;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.GeometryType;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.Polygon;
import com.esri.arcgisruntime.layers.ArcGISMapImageLayer;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.layers.Layer;
import com.esri.arcgisruntime.layers.LayerContent;
import com.esri.arcgisruntime.mapping.GeoElement;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.IdentifyLayerResult;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.vision.world.survey.Interface.OnTouchMapEvent;
import com.vision.world.survey.R;
import com.vision.world.survey.tools.PolygonTools;
import com.vision.world.survey.util.CommonUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.zip.CheckedOutputStream;

/**
 * Created by WANT on 2017/10/4.
 * 操作图层的相关信息
 */
public class QueryManager {
    private static QueryManager mQueryManager=null;
    /**
     * 完成空间查询的图层个数
     */
    public int CountCompleteSelect = 0;

    /**
     * 空间查询目标的个数
     */
    public int CountFeatureSelect = 0;




    public QueryManager(){}

    public static QueryManager getInstance(){
        if(mQueryManager==null){
            mQueryManager=new QueryManager();
        }
        return mQueryManager;
    }

    public List<Object> resultFild=new ArrayList<>();

    /**
     * 查询结果
     */
    public  List<Map<String,Object>> SearchResultFromOperationLayer = new ArrayList<>();

    public  String getSearchResultFromOperationLayer(){
        String strResult ="";
        if(SearchResultFromOperationLayer==null||SearchResultFromOperationLayer.size()==0){
            strResult +="无";
            return strResult;
        }else{
            for(int i=0;i<SearchResultFromOperationLayer.size();i++){
                Map<String,Object> result = SearchResultFromOperationLayer.get(i);
                String strReuslt = "id:'"+ String.valueOf(i)+"',";
                strResult += strReuslt;
                strResult += "Layer:'"+result.get(CommonUtil.KEY_LAYERNAME)+"',";

                Iterator<String> keys = result.keySet().iterator();
                int sizeKeys = result.size()>5?5:result.size();
                int j=0;
                while (keys.hasNext()&&j<sizeKeys){
                    String key = keys.next();
                    if(result.get(key)!=null) {
                        String value = String.valueOf(result.get(key));
                        strResult += key + ":'" + value + "',";
                        j+=1;
                    }
                }
                strResult +="\n";
            }
        }
        return strResult;
    }


    /**
     * 设置地图的点选查询方法
     * @param context
     * @param mapView           地图控件
     * @param touchMapEvent     查询是View层要做的事情
     */
    public void initIdentifyOperation(final Context context, final MapView mapView, final OnTouchMapEvent touchMapEvent){
        mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(context,mapView){

            // override the onSingleTapConfirmed gesture to handle a single tap on the MapView
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                // get the screen point where user tapped
                android.graphics.Point screenPoint = new android.graphics.Point((int) e.getX(), (int) e.getY());
                // clear the result of searching in history
                clearGraphicOverlay(mapView);
                // clear the list of searching in history
                SearchResultFromOperationLayer.clear();
                // refresh the View
                if(touchMapEvent!=null){
                    touchMapEvent.refreshViewOnStartSearch(e);
                }

                // -------------- 点击位置查找 --------------
                int toleranceMap = 5000;
                int tolerancePixel = 1;//Math.round(toleranceMap/Math.round(mapView.getUnitsPerDensityIndependentPixel()));
                //tolerancePixel = 25;//tolerancePixel>100?99:tolerancePixel;//tolerancePixel不能大于100
                searchInMapByIdentify(context,mapView,LayerManager.getInstance().getIdentifyLayers(),screenPoint,tolerancePixel,touchMapEvent);
                return true;
            }
        });
    }

    /**
     * 通过地图的Identify查找对应的位置
     * @param context
     * @param mapView       地图控件
     * @param layer         查询图层
     * @param screenPoint   屏幕点击点
     * @param tolerance     容错距离；单位：像素；不能大于100
     *
     */
    private void searchInMapByIdentify(final Context context, final MapView mapView, final Layer layer, android.graphics.Point screenPoint, int tolerance, final OnTouchMapEvent touchMapEvent) {
        //清空历史选中结果
        SearchResultFromOperationLayer.clear();
        if(layer!=null){
            if(layer instanceof FeatureLayer){
                ((FeatureLayer)layer).clearSelection();
            }
            //单图层查找
            // call identifyLayerAsync, specifying the layer to identify, the screen location, tolerance, types to return, and maximum results
            final ListenableFuture<IdentifyLayerResult> identifyFuture = mapView.identifyLayerAsync(layer, screenPoint, tolerance, false, 1);

            // add a listener to the future
            identifyFuture.addDoneListener(new Runnable() {
                @Override
                public void run() {
                    int Count = 0;
                    try {
                        // get the identify results from the future - returns when the operation is complete
                        IdentifyLayerResult identifyLayerResult = identifyFuture.get();
                        // 处理查找的目标
                        Count = prosessResultFromSearchLayers(context,mapView,identifyLayerResult);

                        // View显示查找结果
                        if(touchMapEvent!=null){
                            touchMapEvent.refreshViewOnSearchSuccess("选中目标个数：" + Count,Count);
                        }

                    } catch(InterruptedException | ExecutionException ex){
                        // must deal with checked exceptions thrown from the async identify operation
                        // View显示失败信息
                        if(touchMapEvent!=null){
                            touchMapEvent.refreshViewOnSearchFailed("查询失败：" + Count,ex);
                        }
                    }

                }
            });
        }else{
            //全部图层查找
            final ListenableFuture<List<IdentifyLayerResult>> identifyFutures = mapView.identifyLayersAsync(screenPoint, tolerance, false,25);
            identifyFutures.addDoneListener(new Runnable() {
                @Override
                public void run() {
                    try {
                        // get the identify results from the future - returns when the operation is complete
                        List<IdentifyLayerResult> identifyLayersResults = identifyFutures.get();

                        int Count = 0;
                        // iterate all the layers in the identify result
                        for (IdentifyLayerResult identifyLayerResult : identifyLayersResults) {
                            Count += prosessResultFromSearchLayers(context,mapView,identifyLayerResult);
                        }

                        // View显示查找结果
                        if(touchMapEvent!=null){
                            touchMapEvent.refreshViewOnSearchSuccess("选中目标个数：" + Count,Count);
                        }
                    } catch (InterruptedException | ExecutionException ex) {
                        // must deal with exceptions thrown from the async identify operation
                        // View显示失败信息
                        if(touchMapEvent!=null){
                            touchMapEvent.refreshViewOnSearchFailed("查询失败：", ex);
                        }
                    }
                }
            });
        }
    }

    /**
     * 选中目标后触发的事件
     * @param context               父页面
     * @param identifiedFeature     点选内容
     * @param layerContent          图层内容
     */
    public int processIdentifyFeatureResult(Context context,Feature identifiedFeature, LayerContent layerContent) {
        FeatureTable table = identifiedFeature.getFeatureTable();
        String strResult = "查询结果";
        List<Field> fields = table.getFields();
        String layerName = layerContent.getName();
        strResult = "图层："+layerName;
        for(Field field:fields){
            String value = (String)identifiedFeature.getAttributes().get(field.getName());
            strResult += "\n"+field.getName()+":"+value+";";
        }
        CommonUtil.showMessage(context,strResult);
        return  1;
    }

    /**
     * 处理各图层搜索后的结果 identify
     */
    private int prosessResultFromSearchLayers(final Context context,final MapView mapView,IdentifyLayerResult identifyLayerResult){
        int Count = 0;
        if (identifyLayerResult.getLayerContent() instanceof FeatureLayer) {
            FeatureLayer featureLayer = (FeatureLayer) identifyLayerResult.getLayerContent();
            // iterate each identified geoelement from the specified layer and cast to Feature
            for (GeoElement identifiedElement : identifyLayerResult.getElements()) {
                if (identifiedElement instanceof Feature) {
                    // access attributes or geometry of the feature, or select it as shown below
                    Feature identifiedFeature = (Feature) identifiedElement;
                    if (featureLayer != null) {
                        Count += processIdentifyImageLayerResult(context,identifiedFeature,featureLayer,mapView);
                        //直接在图层上标注为已选中
                        //featureLayer.selectFeature(identifiedFeature);
                        //Count+=1;
                    }
                }
            }
        }else if(identifyLayerResult.getLayerContent() instanceof ArcGISMapImageLayer){
            //处理ImagLayer的Identify
            List<IdentifyLayerResult> subLayersResults = identifyLayerResult.getSublayerResults();
            Count += iterateIdentifyImageLayerResults(context,subLayersResults,mapView);

        }else{
            // iterate each result in each identified layer, and check for Feature results
            for (GeoElement identifiedElement : identifyLayerResult.getElements()) {
                if (identifiedElement instanceof Feature) {
                    Feature identifiedFeature = (Feature) identifiedElement;
                    // Use feature as required, for example access attributes or geometry, select, build a table, etc...
                    Count += processIdentifyFeatureResult(context,identifiedFeature, identifyLayerResult.getLayerContent());
                }
            }
        }
        return  Count;
    }

    /**
     * 对ImageLayer迭代查询
     * @param context
     * @param identifyLayerResults         查询结果
     * @param mapView                      地图控件
     * @return                             目标个数
     */
    public int iterateIdentifyImageLayerResults(Context context,List<IdentifyLayerResult> identifyLayerResults, MapView mapView) {
        int countMax = 0;
        if ((identifyLayerResults == null) || (identifyLayerResults.size() < 1)) return countMax;
        // a reference to the feature layer can be used, for example, to select identified features

        // iterate all the layers in the identify result
        for (IdentifyLayerResult identifyLayerResult : identifyLayerResults) {
            // for each result, get the GeoElements
            for (GeoElement identifiedElement : identifyLayerResult.getElements()) {

                if (identifiedElement instanceof Feature) {
                    // Map image layer identify results are returned as Features with a null FeatureTable; they cannot be
                    // selected, but you can get the attributes and geometry of them...
                    int count = processIdentifyImageLayerResult(context,((Feature)identifiedElement), identifyLayerResult.getLayerContent(),mapView);
                    countMax += count;
                }
            }

            // for each result, get the sublayer results by recursion
            int count = iterateIdentifyImageLayerResults(context,identifyLayerResult.getSublayerResults(),mapView);
            countMax += count;
        }
        return countMax;
    }

    /**
     * 处理查询到的Feature的内容
     * @param context
     * @param identifiedElement             查询到的对象
     * @param layerContent                  所属图层
     * @param mapView                       地图控件
     */
    public int processIdentifyImageLayerResult(Context context,Feature identifiedElement, LayerContent layerContent, MapView mapView) {
        Geometry geo = processGeoFromeFeature(identifiedElement,mapView);
        int countMax = processRecordFromFeature(context,identifiedElement,layerContent);
        return countMax;
    }

    /**
     * 处理查找到的矢量的显示  identify
     * @param identifiedElement     矢量要素
     * @param mapView               地图控件
     */
    private Geometry processGeoFromeFeature(Feature identifiedElement,MapView mapView){
        Log.i("isFreshIdentify","显示红线区");
        Geometry geo =  identifiedElement.getGeometry();
        Graphic graphic = null;
        if(geo.getGeometryType() == GeometryType.POLYGON){
            //define the fill symbol and outline
            graphic = new Graphic(geo, CommonUtil.SymbolFill);
            mapView.getGraphicsOverlays().get(CommonUtil.IndexGrighicOverlayPolygon).getGraphics().add(graphic);
        }else if(geo.getGeometryType() == GeometryType.POLYLINE){
            graphic = new Graphic(geo,CommonUtil.SymbolOutline);
            mapView.getGraphicsOverlays().get(CommonUtil.IndexGrighicOverlayPolyline).getGraphics().add(graphic);
        }else if(geo.getGeometryType() == GeometryType.POINT){
            graphic = new Graphic(geo,CommonUtil.getSymbolDefaultPictureMapker(mapView.getContext()));
            mapView.getGraphicsOverlays().get(CommonUtil.IndexGrighicOverlayPoint).getGraphics().add(graphic);
        }
        Log.i("isFreshIdentify","显示红线区结束");
        return geo;
    }

    /**
     * 处理查找到结果的属性信息 identify调用
     * @param context
     * @param identifiedElement 查询结果
     * @param layerContent      所属图层
     * @return                  1：成功处理一条；0：失败
     */
    private int processRecordFromFeature(Context context,Feature identifiedElement, LayerContent layerContent){
        Geometry geo = identifiedElement.getGeometry();
        try {
            Map<String, Object> attributes = identifiedElement.getAttributes();
//            identifiedElement.getFeatureTable().getFields();
            String layerName = layerContent.getName();
            /*String geoJson = geo.toJson();*/
            if (layerName != null &&/* geoJson != null*/geo!=null && attributes != null) {
                attributes.put(CommonUtil.KEY_LAYERNAME, layerName);
                /*attributes.put(Util.KEY_GEOJSON, geoJson);*/
                attributes.put(CommonUtil.KEY_GEO,geo);
                SearchResultFromOperationLayer.add(attributes);
            }else{
                return 0;
            }
        }catch (Exception ex){
            CommonUtil.showMessage(context,ex.getMessage());
            return 0;
        }
        return 1;
    }


    /**
     * 处理查找到结果的属性信息  范围查找调用 search调用
     * @param context
     * @param identifiedElement 查询结果
     * @param layerContent      所属图层
     * @return                  1：成功处理一条；0：失败
     */
    private int processRecordFromFeature(Context context,Feature identifiedElement, List<Field> fields,LayerContent layerContent){
        Geometry geo = identifiedElement.getGeometry();
        try {
            Map<String, Object> attributes = identifiedElement.getAttributes();
            Map<String, Object> result =new HashMap<String, Object>();//attributes;
            String layerName = layerContent.getName();
            /*String geoJson = geo.toJson();*/
            if (layerName != null &&/* geoJson != null*/ geo!=null&& attributes != null) {
                result.put(CommonUtil.KEY_LAYERNAME, layerName);
                /*result.put(Util.KEY_GEOJSON,geoJson);*/
                result.put(CommonUtil.KEY_GEO,geo);
                for(Field field:fields){
//                    String names=field.getName();
//                    String namesss=attributes.get(field.getName()).toString();
                    result.put(field.getName(),attributes.get(field.getName()));
                }
                SearchResultFromOperationLayer.add(result);
//                SearchResultFromOperationLayer.add(attributes);
            }else{
                return 0;
            }
        }catch (Exception ex){
            CommonUtil.showMessage(context,ex.getMessage());
            return 0;
        }
        return 1;
    }


    /**
     * 根据输入内容请求服务查询  search调用
     * @param context
     * @param mapView   地图控件
     * @param f_caption 字段名
     * @param value     字段值
     * @param viewEvent 界面更新
     *
     */
    public void initQuaryByField(final Context context, final MapView mapView, final String f_caption, final String value,final OnTouchMapEvent viewEvent) {
        //refresh view
        if(viewEvent!=null){
            viewEvent.refreshViewOnStartSearch(context.getResources().getString(R.string.search_by_field));
        }

        // clear the result of searching in history
        clearGraphicOverlay(mapView);

        // clear the result of searching in history
        QueryManager.getInstance().SearchResultFromOperationLayer.clear();

        // create objects required to do a selection with a query
        QueryParameters query = new QueryParameters();
        //make search case insensitive
        //String strQuery = "upper("+f_caption+") LIKE '%" + value + "%'";
        String strQuery = f_caption+" LIKE '%" + value + "%'";
        query.setWhereClause(strQuery);
        query.setReturnGeometry(true);

        // call select features
        final ListenableFuture<FeatureQueryResult> future =  LayerManager.getInstance().getFeatureLayerQuaryField().getFeatureTable().queryFeaturesAsync(query);

        // add done loading listener to fire when the selection returns
        future.addDoneListener(new Runnable() {
            @Override
            public void run() {
                try {
                    // call get on the future to get the result
                    FeatureQueryResult result = future.get();
                    int countMax = 0;
                    Iterator<Feature> results = result.iterator();
                    List<Field> fields = result.getFields();
                    // check there are some results
                    while (results.hasNext()) {

                        // get the extend of the first feature in the result to zoom to
                        Feature feature = results.next();
                        Envelope envelope = feature.getGeometry().getExtent();

                        // TODO: 2017/10/8 显示结果
                        processGeoFromeFeature(feature,mapView);
                        /*countMax += processRecordFromFeature(context,feature,getFeatureLayerQuaryField());*/
                        countMax += processRecordFromFeature(context,feature,fields,LayerManager.getInstance().getFeatureLayerQuaryField());
                        //Select the feature
//                        mFeaturelayer.selectFeature(feature);
                    }

                    String info = "选中目标个数：" + countMax;
                    Log.i("属性查找——成功",info);
                    if(viewEvent!=null){
                        viewEvent.refreshViewOnSearchSuccess(info,countMax);
                    }
                } catch (Exception e) {
                    String info = "Feature search failed for: " + value + ". Error=" + e.getMessage();
                    Log.e("属性查找——失败", info);
                    if(viewEvent!=null){
                        viewEvent.refreshViewOnSearchFailed(info,e);
                    }
                }
                CommonUtil.dismissProgressDialog();
            }
        });
    }

    /**
     * 设置地理围栏查找方法  boundary调用
     * 查找当前位置周边distance米内的目标，距离distance允许用户在系统设置中进行配置
     * @param context
     * @param mapView           地图控件
     *                           当为null时对地图中所有操作图层进行查询；
     *                           不为null时对layer进行查询
     */
    public void initSelectByLocationBoundary(final Context context, final MapView mapView,final OnTouchMapEvent viewRefreshEvent){
        LocationDisplay locationDisplay = mapView.getLocationDisplay();
        if(!locationDisplay.isStarted()){
            locationDisplay.startAsync();
        }
        // get the location about the device
        Point pointMyLocation =  locationDisplay.getMapLocation();

        // create select envelope by tolerance setting by users
        /*Envelope envelope = new Envelope(
                pointMyLocation.getX() - Util.MapSelectDistance,
                pointMyLocation.getY() - Util.MapSelectDistance,
                pointMyLocation.getX() + Util.MapSelectDistance,
                pointMyLocation.getY() + Util.MapSelectDistance,
                mapView.getSpatialReference());*/
        // create circle select boundary
        Polygon boundaryCircle = CommonUtil.GetCircleBoundary(pointMyLocation,CommonUtil.MapSelectDistance,64,mapView.getMap().getSpatialReference());

        //todo 绘制选择区域  不显示选择缓冲区时刻意隐藏
        Graphic graphic = new Graphic(boundaryCircle, CommonUtil.SymbolFill_SelectBoundary);
        mapView.getGraphicsOverlays().get(CommonUtil.IndexGrighicOverlaySelectBoundary).getGraphics().add(graphic);


        //refresh the view
        if(viewRefreshEvent!=null){
            String info = context.getResources().getString(R.string.search_by_boundary);
            viewRefreshEvent.refreshViewOnStartSearch(info);
        }
        if(LayerManager.getInstance().getFeatureLayerSelectByGeometry()!=null&&LayerManager.getInstance().getFeatureLayerSelectByGeometry().length>0) {
            //TODO 1.先进行当前位置是否在红线区内的搜索
            //TODO 2.若当前位置不在任何缓冲区内，设置圆形缓冲区查找
            searchInLayersByGeometry(pointMyLocation,context, mapView, LayerManager.getInstance().getFeatureLayerSelectByGeometry(), boundaryCircle, viewRefreshEvent);
        }else{
            if(viewRefreshEvent!=null){
                String info = "没有可供查询的图层";
                Exception ex = new Exception();
                viewRefreshEvent.refreshViewOnSearchFailed(info,ex);
            }
        }
    }

    /**
     * 查询在范围内或与范围相交的要素  Boumdary调用
     * @param context
     * @param mapView           地图控件
     * @param layers            查询图层
     * @param geo               查询范围
     * @param touchMapEvent     查询后View要做的
     */
    private void searchInLayersByGeometry(final Point myLocation,final Context context, final MapView mapView, final FeatureLayer[] layers, Geometry geo,final OnTouchMapEvent touchMapEvent) {
        Log.i("isFreshIdentify","开始Boundary搜索");
        SearchResultFromOperationLayer.clear();
        //重置已查询图层的个数
        CountCompleteSelect = 0;
        //重置空间查询的结果个数
        CountFeatureSelect = 0;
        //设置查询条件
        QueryParameters query = new QueryParameters();
        //设置查询范围
        query.setGeometry(geo);
        //查询方式为相交
        query.setSpatialRelationship(CommonUtil.SelectRelationship);
        Log.i("sort","layers：" + layers.length);
        // call select features
        for(int i=0;i<layers.length;i++) {
            final FeatureLayer layer = layers[i];
            final ListenableFuture<FeatureQueryResult> future = layer.selectFeaturesAsync(query, FeatureLayer.SelectionMode.NEW);
            // add done loading listener to fire when the selection returns
            future.addDoneListener(new Runnable() {
                @Override
                public void run() {
                    CountCompleteSelect += 1;
                    try {
                        //call get on the future to get the result
                        FeatureQueryResult result = future.get();

                        // create an Iterator
                        Iterator<Feature> iterator = result.iterator();
                        List<Field> fields = result.getFields();
                        Feature feature = null;

                        while (iterator.hasNext()) {
                            // get the extend of the first feature in the result to zoom to
                            feature = iterator.next();
                            Envelope envelope = feature.getGeometry().getExtent();

                            // 显示结果
                            processGeoFromeFeature(feature, mapView);
                            //CountFeatureSelect += processRecordFromFeature(context, feature, layer);
                            CountFeatureSelect += processRecordFromFeature(context, feature, fields, layer);
                            //Select the feature
//                        mFeaturelayer.selectFeature(feature);
                        }
                        // View显示查找结果
                        if(touchMapEvent!=null){
                            Log.i("sort","选中目标个数：" + CountFeatureSelect);
                                touchMapEvent.refreshViewOnSearchSuccess("选中目标个数：" + CountFeatureSelect,CountFeatureSelect);

                        }
                    } catch(InterruptedException | ExecutionException ex){
                        // must deal with checked exceptions thrown from the async identify operation
                        //
                        if(touchMapEvent!=null){
                            touchMapEvent.refreshViewOnSearchFailed("查询失败：\n"+layer.getName(), ex );
                        }

                    }
                }
            });
        }
    }

    /**
     * 空间查找是否完成
     * @return
     */
    public boolean isSelectByGeometryComplete(){
        if(CountCompleteSelect==LayerManager.getInstance().getFeatureLayerSelectByGeometry().length){
            return true;
        }
        return  false;
    }


    /**
     * 清空GraphicOverlay 中的元素
     * @param mapView   地图控件
     */
    public void clearGraphicOverlay(MapView mapView){
        if(mapView.getGraphicsOverlays().size()==0) {
            LayerManager.getInstance().initGraphicOverlay(mapView);
        }
        mapView.getGraphicsOverlays().get(CommonUtil.IndexGrighicOverlayPolygon).getGraphics().clear();
        mapView.getGraphicsOverlays().get(CommonUtil.IndexGrighicOverlayPolyline).getGraphics().clear();
        mapView.getGraphicsOverlays().get(CommonUtil.IndexGrighicOverlayPoint).getGraphics().clear();
        mapView.getGraphicsOverlays().get(CommonUtil.IndexGrighicOverlaySelectBoundary).getGraphics().clear();
        mapView.getGraphicsOverlays().get(CommonUtil.IndexGrighicOverlayShowResult).getGraphics().clear();
    }


    public void disSort(Point myPosition) throws IOException {
        double temp0;
        double tempi;
        Map<String,Object> res=null;
//        if(SearchResultFromOperationLayer.size()>0) {
//            Geometry geo = (Geometry) SearchResultFromOperationLayer.get(0).get(CommonUtil.KEY_GEO);
//            if(PolygonTools.Contains(myPosition,geo)) {
//                res=SearchResultFromOperationLayer.get(0);
//                res.put("Distance","在红线区内");
//                SearchResultFromOperationLayer.clear();
//                SearchResultFromOperationLayer.add(res);
//            }else{
//                temp0 = PolygonTools.pointToPolygons(myPosition, geo);
//                SearchResultFromOperationLayer.get(0).put("Distance",""+temp0);
//            }
//        }
        for(int i=0;i<SearchResultFromOperationLayer.size();i++){
            Geometry geo= (Geometry) SearchResultFromOperationLayer.get(i).get(CommonUtil.KEY_GEO);
            if(PolygonTools.Contains(myPosition,geo)) {
                res=SearchResultFromOperationLayer.get(0);
                res.put("Distance",-1);
                SearchResultFromOperationLayer.clear();
                SearchResultFromOperationLayer.add(res);
            }else{
                tempi= PolygonTools.pointToPolygons(myPosition, geo);
                SearchResultFromOperationLayer.get(i).put("Distance",tempi);
//                res=SearchResultFromOperationLayer.get(i);
//                if(tempi<temp0){
//                    temp0=tempi;
//                    SearchResultFromOperationLayer.get(i).put("Distance",""+tempi);
//                    SearchResultFromOperationLayer.add(0,res);
//                }
            }
        }
        Log.i("sort result",""+ "排序前");
        for(int i=0;i<SearchResultFromOperationLayer.size();i++){
            Log.i("sort result",""+SearchResultFromOperationLayer.get(i).get("Distance"));
        }
            Collections.sort(SearchResultFromOperationLayer,new Comparator< Map<String,Object>>() {
                @Override
                public int compare(Map<String,Object> o1, Map<String,Object> o2) {
                    //升序
                    return ((Double)o1.get("Distance")).compareTo(((Double)o2.get("Distance")));
                }
            });
        Log.i("sort result",""+ "排序后");
        for(int i=0;i<SearchResultFromOperationLayer.size();i++){
            Log.i("sort result",""+SearchResultFromOperationLayer.get(i).get("Distance"));
        }

    }

}
